﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Apollo
{
    public delegate void ActionCompletionHandler(object obj);

    public class ActionContext
    {
        public ActionContext() {
            this.State = ActionState.Unknown;
            this.Messages = new List<ActionMessage>();
            this.InnerContexts = new List<ActionContext>();
        }
        public ActionContext(ActionMessage message) : this() {
            this.AddMessage(message);
        }

        public IList<ActionContext> InnerContexts { get; set; }

        public event ActionCompletionHandler OnActionSuccess;
        public event ActionCompletionHandler OnActionFailed;

        public ActionState State { get; set; }

        public IList<ActionMessage> Messages { get; set; }

        /// <summary>
        /// Using this will also change the State accordingly
        /// </summary>
        /// <param name="message"></param>
        public void AddMessage(ActionMessage message) {
            switch (message.Type) { 
                case ActionMessageType.Info:
                case ActionMessageType.Warning:
                    this.State = ActionState.Succesful;
                    break;
                case ActionMessageType.Error:
                case ActionMessageType.System:
                case ActionMessageType.Security:
                    this.State = ActionState.Failed;
                    break;
            }

            this.Messages.Add(message);
        }
        public void AddMessage(ActionMessage message, ActionState state) {
            this.AddMessage(message);
            this.State = state;
        }

        public void AddRange(IList<ActionMessage> messages) {
            foreach (ActionMessage message in messages)
                this.Messages.Add(message);
        }

        public void MarkActionEnd(object obj, bool withSuccess) {
            if (withSuccess && OnActionSuccess != null)
                OnActionSuccess(obj);

            if (!withSuccess && OnActionFailed != null)
                OnActionFailed(obj);
        }
    }
}
